<!--
°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°
° 	HONORE Perrine
° 	GIOVANETTI Romain
°
° 	Master 2 - E-services TWA Project
°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°
-->
<!doctype html>
<html>
<head>
	<meta charset='UTF-8' />	
	<link rel="stylesheet" href="./style.css">
    <link rel="stylesheet" href="./modern.css">
    <link href="./modern-responsive.css" rel="stylesheet">
    <link href='http://fonts.googleapis.com/css?family=Open+Sans:300' rel='stylesheet' type='text/css'>

	<script type="text/javascript" src="./javascript/mirrorjs.min.js"></script>
	<script type="text/javascript" src="./websocketclient.js"></script>
	<script type="text/javascript" src="./javascript/tools.js"></script>
	<script type="text/javascript" src="./javascript/settings.js"></script>
	<script src="./javascript/sha1.js"></script>

	<script>
		var Server;
		var ServerId;
		var Login;
		var MotdePasse;
		var myId = 0;
		var serverready = 0;
		var salt = 0;
		var activeConversation = null;

		getMessagesDeamon();

		function PromptMessage() {
		    //ServerId = prompt("Numéro du serveur", "1");
		    ServerId = 1;
		}

		function PromptLogin() {
		    Login=document.forms["logfrm"]["loginimpt"].value;
		}


		function PromptPassword() {
		    MotdePasse=document.forms["logfrm"]["passwordimpt"].value;
		}

		function demandeDeConversation(nom)
		{
			send("/getConversationWith#" + nom);
			document.getElementById('contactName').firstChild.nodeValue = nom;
			activeConversation = nom;

			var container = document.getElementById('contactslist');
			for(i in container.childNodes)
			{
				if(container.childNodes[i].childNodes!= null)
				{
					if(activeConversation == container.childNodes[i].childNodes.item(1).innerHTML)
					{
						container.childNodes[i].childNodes.className = "activeContact";
					}
				}
			}
		}

		function getMessagesDeamon() {
			if(activeConversation != null)
			{
				demandeDeConversation(activeConversation);
			}
			setTimeout("getMessagesDeamon()", 3000); 
	    }



		function envoiduMessage(MessageAEnvoyer, destinataire)
		{
			send("/messageAEnvoyerA#" + destinataire + "#" + MessageAEnvoyer);
		}

		function send( text ) {
			Server.send( 'message', text );
		}
		
		function insererLogin()
		{
			 var leforumulaire = '<div id="logincontenair"><img src="./Apps-App-Store-alt-Metro-icon.png" id="chatlogo" /><div id="loginfields"><h3>Login : </h3><form id="logfrm"><div class="input-control text" ><input type="text" id="loginimpt"value="'+localStorage['loginIOHU']+'" onfocus="if(this.value == this.defaultValue) this.value = \'\'"/><span class="helper"></span></div><h3>Password : </h3><div class="input-control password"><input id="passwordimpt" type="password" /><span class="helper"></span></div><input id="gogogo" type="submit" value="Submit" onclick="valider();return false;"/></div></form>';
  	
  			document.getElementById('frame').innerHTML= leforumulaire;
		}
		
		function insererCube()
		{
			var lecube = "<iframe src='./aIntegrer/cube/cube3D.html' style='border: 0; height: 500px; width: 600px; margin: auto; display: block;' ></iframe>";
			document.getElementById('frame').innerHTML= lecube;
		}
		
		function insererChat()
		{
			var lechat = "Le Chat";
			document.getElementById('frame').innerHTML= "";
			document.getElementById('contenair').style.height = 'auto';

			var leTextaera = document.getElementById("leformulaireAmessage");
			leTextaera.addEventListener("keydown", keyDownTextField, false);
		}

		function keyDownTextField (e) {
			var keyCode = e.keyCode;
			if(keyCode==13) {
				if(activeConversation!= null)
				{
					var texte = document.forms["formmessage"]["leformulaireAmessage"].value;
    				envoiduMessage(texte, activeConversation);
    				var texte = document.forms["formmessage"]["leformulaireAmessage"].value = "";
    			}
  			}
		}

		
		function valider()
		{
			if(serverready == 1)
			{
				 	PromptLogin();
				 	PromptPassword();
				 	var MotdePasseSalt = MotdePasse+salt;
					var MotdePasseChiffre = CryptoJS.SHA1(MotdePasseSalt);
				 	send("/login#" + Login + "#" + MotdePasseChiffre + "#" + myId + ">" + ServerId);
			}
		}

		function refreshContactList(contactsArray)
		{
			localStorage['loginIOHU'] = Login;
			var contacts = contactsArray.substring(1,contactsArray.length-1).split(",");
			if(contacts.length == 0 ||  contacts.length == 1)
			{
			}
			else
			{
				var container = document.getElementById('contactslist');
				$("#contactslist").empty();
				for(var i = 0; i< contacts.length; i++)
				{
					if(Login != contacts[i].split('"')[1])
					{

						var new_element = document.createElement('li');
						new_element.innerHTML = '<img class="contactsAvatar imgonline" src="./bluemanm.png" /><a href="javascript:demandeDeConversation(\''+contacts[i].split('"')[1]+'\');">'+contacts[i].split('"')[1]+'</a>';
						if(activeConversation == contacts[i].split('"')[1])
						{
							new_element.className = "activeContact";
						}
						container.insertBefore(new_element, container.firstChild);
					}
				}
			}
		}

		function getContactsDeamon() {
			send("/getListAmis#" + myId + ">" + ServerId);
	        setTimeout("getContactsDeamon()", 5000); 
	    }

	    function afficherConversation(conversation)
	    {
	    	eval("var oMessages = " + conversation);
	    	var container = document.getElementById('laconversation');

			$("#laconversation").empty();
	    	for (i in oMessages)
	    	{
	    		var new_element = document.createElement('li');
	    		new_element.style.minHeight = "70px";

	    		if(oMessages[i].message_sender != Login)
	    		{
	    			new_element.className = "bg-color-blue";
	    			var codeHTML = '<b class="sticker sticker-left sticker-color-blue"></b><div class="avatar"><img src="./bluemanm.png" width="40" height="40"/></div><div class="reply">';

	    			var date = new Date(oMessages[i].message_timestamp*1000);

	    			codeHTML += '<div class="date">' + date.getDate() +"/"+(date.getMonth()+1) + "/" + date.getFullYear()+' '+date.getHours()+'h'+ date.getMinutes()+'</div>';
	    			codeHTML += '<div class="author">'+oMessages[i].message_sender +'</div>';
	    			codeHTML += '<div class="text">'+oMessages[i].message_message +'</div></div>';

	    		}
	    		else
	    		{
	    			new_element.className = "bg-color-blueDark";
	    			var codeHTML = '<b class="sticker sticker-right sticker-color-blueDark"></b><div class="avatar"><img src="./bluemanm.png" width="40" height="40"/></div><div class="reply">';

	    			var date = new Date(oMessages[i].message_timestamp*1000);

	    			codeHTML += '<div class="date">' + date.getDate() +"/"+(date.getMonth()+1) + "/" + date.getFullYear()+' '+date.getHours()+'h'+ date.getMinutes()+'</div>';
	    			codeHTML += '<div class="author">'+oMessages[i].message_sender +'</div>';
	    			codeHTML += '<div class="text">'+oMessages[i].message_message +'</div></div>';
	    		}


				new_element.innerHTML = codeHTML;
				container.appendChild(new_element);
	    	}
	    	$('#messages').animate({scrollTop: $('#messages').height()}, 1000);

	    }
		
		$(document).ready(function() {
			Server = new FancyWebSocket('ws://127.0.0.1:9300');

			$('#message').keypress(function(e) {
				if ( e.keyCode == 13 && this.value ) {
					send( this.value );

					$(this).val('');
				}
			});
			
			insererLogin();

			//Let the user know we're connected
			Server.bind('open', function() {
				send("/openConnection#" + myId + ">" + ServerId);
			});

			//OH NOES! Disconnection occurred.
			Server.bind('close', function( data ) {
			});

			//Log any messages sent from server
			Server.bind('message', function( payload ) {

				var messageRecu = payload.split(' __ws__ ')[1];
				var clientId = payload.split(' __ws__ ')[0];

				/* Si une commande est reçue, on la traite */
				if(messageRecu.charAt(0) == '/')
				{
					var commande = messageRecu.split('#')[0];
					var tailleTab = messageRecu.split('#').length;
					var findeTab = messageRecu.split('#')[tailleTab-1];
					var idEnvoye = findeTab.split('>')[1];

					if(commande == "/yourIdIs"){
						if(myId == 0)
						{
							myId = messageRecu.split('#')[1];
						}
					}
					else
					{
						if(idEnvoye == myId)
						{
							switch (commande) {

								 case "/serveurReady":
								 	serverready = 1;
								 	salt = messageRecu.split('#')[1];
								 break;

								 case "/loginOK":
								 	insererCube();
								 	setTimeout('insererChat()',5000);
								 	getContactsDeamon();
								 break;

								 case "/listeDesConnectes" :
									lesContacts = messageRecu.split('#')[1];
								 	refreshContactList(lesContacts);
								 break;

								 case "/conversationWith" :
								 	afficherConversation(messageRecu.split('#')[2]);
								 break;

								 default: 
								 	verbose("Commande invalide");
								 break;
							}
						}
					}
				}
			});
			PromptMessage();
			Server.connect();
		});
	</script>
</head>

<body>
 	<header>
  		<div id="imglogo"></div>
  		<div id="titrelogo">IOHU</div>
  	</header>

  	<div id="frame">
  	</div>

 	<div id="contenair">
		<nav>
			<span class="titre">Contacts(s)</span>
		  <ul id="contactslist">
		  </ul>
		</nav>
		<section>
			<span class="titre" id="contactName">Choisissez un contact dans la liste de gauche.</span>
			<div id="messages">

			<ul  class="replies" id="laconversation">
			</ul>
			</div>
			<form id="formmessage">
				<div id="writemessage">
		   			<div class="input-control textarea" style="margin-left: 40px;width: 355px;">
		        		<textarea name="leformulaireAmessage" id="leformulaireAmessage">
		        		</textarea>
		    		</div>
		    	</div>
			</form>
		</section>
		<hr>
	</div>
	<footer>
		© 2012 Honoré & Giovanetti.
	</footer>	
</body>
</html>